import React, { memo, useEffect } from 'react';
import _ from 'lodash';
import { withRouter, useModel } from 'umi';
import KeepAlive, { useAliveController } from 'react-activation';
import { TransitionGroup, CSSTransition } from 'react-transition-group';
import { getOriginalPath } from '@/utils/routeFormat';
import './index.less';

const animationNames = {
  PUSH: 'forward',
  POP: 'back',
  REPLACE: 'fade',
};

const RouteComponent = memo(({ pathname, children }) => (
  <div className="transfer-route-container">
    <KeepAlive cacheKey={pathname} name={pathname}>
      {children}
    </KeepAlive>
  </div>
));

export default withRouter(({ location, history, children }) => {
  const { dropScope } = useAliveController();
  const { initialState } = useModel('@@initialState');
  const { routePathList } = initialState;
  const currentHistoryPath = getOriginalPath(location.pathname);
  const isRouteCache = !!_.last((routePathList || {})[currentHistoryPath])?.keepAlive;

  useEffect(() => {
    return () => {
      if (!isRouteCache) {
        // TODO bug：无需缓存的页面，若在过渡动画结束前再次激活，则出现缓存问题，未修复
        dropScope(currentHistoryPath);
      }
    };
  }, [currentHistoryPath]);

  return (
    <TransitionGroup
      component={null}
      childFactory={(child) =>
        React.cloneElement(child, {
          classNames: animationNames[history.action],
        })
      }
    >
      <CSSTransition key={currentHistoryPath} timeout={300}>
        <RouteComponent pathname={currentHistoryPath}>{children}</RouteComponent>
      </CSSTransition>
    </TransitionGroup>
  );
});
